package com.example.dragon.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.dragon.adpter.PengDingAdpter;
import com.example.dragon.adpter.ServiceAdpter;
import com.example.dragon.bean.OrderBean;
import com.example.dragon.common.Common;
import com.example.dragon.dialog.MessageDialog;
import com.example.dragon.xmf.MainActivity;
import com.example.dragon.xmf.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class InServiceFragment extends Fragment {

    private RecyclerView mrecyclerView;
    private List<OrderBean> morderList = new ArrayList<>();
    private ServiceAdpter serviceAdpter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private MessageDialog messageDialog;
    int i=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_in,null);
        initControls(view);
        return view;
    }
    private void initControls(View view){
        mrecyclerView = (RecyclerView)view.findViewById(R.id.servierRecycle);
        mrecyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        mrecyclerView.setItemAnimator(new DefaultItemAnimator());
        swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swrefresLayout);
        swipeRefreshLayout.setColorSchemeColors(R.color.styleColor);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        morderList.clear();
                        i=i+12;
                        getOrder(i);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        mHandler.sendEmptyMessage(1);
                    }
                }).start();
            }
        });
//        getOrder();
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            //可见
            getOrder(i);
        }else{
            //不可见
        }
    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    swipeRefreshLayout.setRefreshing(false);
                    serviceAdpter.notifyDataSetChanged();
                    //swipeRefreshLayout.setEnabled(false);
                    break;
                default:
                    break;
            }
        }
    };



    private void getOrder(int i){
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"Orders&a=getList")
                .addParams("token", MainActivity.TOKEN)
                .addParams("group","1")
                .addParams("status","1")
                .addParams("nowpage","1")
                .addParams("perpage",i+"")
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                String num = datas.getString("num");
                                JSONArray list = datas.getJSONArray("list");
                                if (list.length()==0){
                                    new MessageDialog("","暂无订单","确定",getContext());
                                }else {
                                    morderList.clear();
                                    for (int i=0;i<list.length();i++){
                                        JSONObject json = list.getJSONObject(i);
                                        Boolean isDriver = !json.isNull("driver");
                                        JSONObject driver = null;
                                        if(isDriver){
                                            driver = json.getJSONObject("driver");
                                        }
                                        Boolean isdrivers = !json.isNull("drivers");
                                        JSONObject  drivers = json.getJSONObject("drivers");
                                        morderList.add(new OrderBean(
                                                json.getString("orders_id"),
                                                json.getString("worktime"),
                                                json.getString("name"),
                                                json.getString("mobile"),
                                                json.getString("address"),
                                                json.getString("fee"),
                                                json.getString("lng"),
                                                json.getString("lat"),
                                                json.getString("fare"),
                                                isDriver?driver.getString("driver_id"):null,
                                                isDriver?driver.getString("avatar"):null,
                                                isDriver?driver.getString("name"):null,
                                                isDriver?driver.getString("lng"):null,
                                                isDriver?driver.getString("lat"):null,
                                                json.getString("status"),
                                                drivers.getString("stars")

                                        ));
                                    }
                                    serviceAdpter = new ServiceAdpter(getActivity(),morderList);
                                    mrecyclerView.setAdapter(serviceAdpter);
                                }
                                Log.i("dates",num+datas);
                            }else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
